/*
 Copyright (c) 2013, Ike Yousuf <admin@kudodev.com>
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 names of its contributors may be used to endorse or promote products
 derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.kudo.gdx.ui;

import com.badlogic.gdx.InputMultiplexer;
import com.kudo.gdx.ui.components.TextField;
import com.kudo.gdx.ui.components.Frame;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.kudo.gdx.Graphics;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Ike
 */
public class UIDisplay extends InputMultiplexer {

    private Map<Integer, Boolean> pressedKeys = new HashMap<>();
    private RootContainer root;
    private ZComparator zCompare = new ZComparator();
    private boolean childrenDirty = true;
    public static boolean debugMode = false, showDebugPanel = false;
    public DebugPanel debugPanel = null;
    public Container activeFrame = null;
    public TextField activeTextField = null;

    public UIDisplay() {
        root = new RootContainer(this);
        debugPanel = new DebugPanel(root);
    }

    public void update(float delta) {
        if (showDebugPanel) {
            debugPanel.update(delta);
        }
    }

    public void setDebugPanel(DebugPanel d) {
        debugPanel = d;
    }

    public void setDebugMode(boolean b) {
        debugMode = b;
    }

    public void setShowDebugPanel(boolean b) {
        showDebugPanel = b;
    }

    public Container getRootPane() {
        return root;
    }

    public void addFrame(Container c) {
        childrenDirty = true;
        if (c instanceof Frame) {
            ((Frame) c).getResizeButton().setLocation(c.getWidth() - 15, c.getHeight() - 15);
        }
        addProcessor(c.getInput());
        root.add(c);
    }

    public void render(Graphics g) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = 0; i < root.getContainers().size(); i++) {
                root.getContainers().get(i).render(g);
            }
        }
        if (showDebugPanel) {
            debugPanel.render(g);
        }
        if (debugMode) {
            for (int i = 0; i < root.getContainers().size(); i++) {
                if (root.getContainers().get(i).getVisible()) {
                    g.shapeRendererBegin(ShapeRenderer.ShapeType.Rectangle);
                    root.getContainers().get(i).renderDebug(g);
                    g.shapeRendererEnd();
                }
            }
        }
    }

    public List<Container> getChildren() {
        return root.getContainers();
    }

    public TextField getActiveTextField() {
        return activeTextField;
    }

    public void setActiveTextField(TextField comp) {
        if (activeTextField != null) {
            activeTextField.setActive(false);
        }
        activeTextField = comp;
        if (comp != null) {
            activeTextField.setActive(true);
        }
    }

    public Map<Integer, Boolean> getPressedKeys() {
        return pressedKeys;
    }

    private class ZComparator implements Comparator {

        @Override
        public int compare(Object o1, Object o2) {
            Component c1 = (Component) o1;
            Component c2 = (Component) o2;
            int res;
            if (c1 == null || c2 == null || c1.equals(c2)) {
                res = 0;
            } else {
                res = new Integer((int) c1.getZIndex()).compareTo((int) c2.getZIndex());
            }
            return res;
        }
    }

    public void ensureZOrder() {
        if (childrenDirty) {
            Collections.sort(root.getContainers(), zCompare);
            childrenDirty = false;
        }
    }

    @Override
    public boolean keyDown(int keycode) {
        pressedKeys.put(keycode, true);
        if (!root.getContainers().isEmpty()) {
            if (activeTextField != null) {
                activeTextField.getInput().keyDown(keycode);
                return true;
            }
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().keyDown(keycode)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        pressedKeys.put(keycode, false);
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().keyUp(keycode)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().keyTyped(character)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    boolean b = comp.getInput().touchDown(screenX, screenY, pointer, button);

                    if (!b) {
                        if (comp == activeFrame && comp.contains(screenX, screenY)) {
                            return true;
                        }
                    }

                    if (comp != activeFrame && (b || comp.contains(screenX, screenY))) {
                        if (activeFrame != null) {
                            activeFrame.setZIndex(0);
                            activeFrame.setActive(false);
                        }
                        activeFrame = comp;
                        activeFrame.setZIndex(400);
                        activeFrame.setActive(true);
                        childrenDirty = true;
                    } else if (comp == activeFrame && !b && !comp.contains(screenX, screenY)) {
                        activeFrame.setActive(false);
                        activeFrame.setZIndex(0);
                        activeFrame = null;
                    }

                    if (b) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().touchUp(screenX, screenY, pointer, button)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().touchDragged(screenX, screenY, pointer)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().mouseMoved(screenX, screenY)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        if (!root.getContainers().isEmpty()) {
            ensureZOrder();
            for (int i = root.getContainers().size() - 1; i >= 0; i--) {
                Container comp = root.getContainers().get(i);
                if (comp.getEnabled() && comp.getVisible()) {
                    if (comp.getInput().scrolled(amount)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
